package com.rzx.dim4status.controller;

import com.rzx.dim4status.utils.Result;
import com.rzx.dim4status.service.PlaceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

@RestController
@RequestMapping(value = "/placeState")
public class PlaceController {//存储Id，在线online上机数与离线offline数

    @Resource
    private PlaceService placeService;
    @Autowired
    StringRedisTemplate stringRedisTemplate;

//    @GetMapping("/findPlaceStateById/{id}")
//    public Result getPlaceStateById(@PathVariable String id){
//        Map<String,String> savePlaceStateById = new HashMap<>();
//        savePlaceStateById.put(id, (String) stringRedisTemplate.opsForHash().get("placeMessage",id));
//        return Result.ok("查询成功",savePlaceStateById);
//    }
    @GetMapping("/findPlaceStateById/{placeId}")
    public Result getPlaceStateById(@RequestBody @PathVariable String placeId) {
        if (stringRedisTemplate.opsForHash().hasKey("placeMessage",placeId)){
            Map<String, String> savePlaceStateById = placeService.findPlaceStateById(placeId);
            return Result.ok("查询成功", savePlaceStateById);
        }else {
            return Result.fail("无所输入的ID");
        }
    }

    @PutMapping("/updatePlaceState")//每插入或更改数据时，同步Global状态
    public Result updatePlaceState(@RequestBody Map<String, String> map) {
        String id = map.get("placeStateId");
        Integer online = Integer.valueOf(map.get("online"));
        Integer offline = Integer.valueOf(map.get("offline"));
        placeService.changePlaceState(id, online, offline);
        return Result.ok("更新成功", map);
    }//前端已实现

    @DeleteMapping("/delPlaceStateById/{id}")
    public Result delPlaceStateById(@PathVariable String id) {
        if (stringRedisTemplate.opsForHash().hasKey("placeMessage", id)) {
            stringRedisTemplate.opsForHash().delete("placeMessage", id);
            placeService.addPlaceComputer();
            return Result.ok("删除成功");
        }
        return Result.fail("找不到删除目标");
    }

    @GetMapping("/findAllPlaceState")
    public Result placeStateFindAll() {
        placeService.addPlaceComputer();
        return Result.ok(placeService.findAllPlace());
    }
}
